const app = getApp()
const {viewHeight,Toast}  = app.globalData
import {getStaffInfo,updateDoctorToDoTasks} from "../../../../api/wenzhen"
import {updateChatRoomContent,findChatRoomContentById,findChatRoomInfoById} from "../../../../api/chatRoom"
import {getUserInfo} from "../../../../api/userInfo"
import {formatTime} from "../../../../utils/utils"
import {send,SocketTask} from "../../../../utils/socketTask"
import {getViewHeight} from "../../../../utils/utils"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    chatContent:[],
    inputValue:"",
    viewHeight,
    chatContentBoxHeight:viewHeight - 120,
    count:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    // 监听是否有新消息
    SocketTask.onMessage(res=>{
      let {data} = res
      data = JSON.parse(data)
      // console.log("wenzhen",data);
      if(data.haveNewMsg){
        this.findContentByChatRoomId(this.data.chatRoomId)
      }
    })

    let {chatRoomId} = options
    // console.log(chatRoomId);
    // 根据 chatRoomId 获取 userId 与 staffId
    let {userId,staffId} = await findChatRoomInfoById(chatRoomId)
    // 查 staffInfo（doctorInfo） 与 userInfo
    let userInfo = await getUserInfo()
    let staffInfo = await getStaffInfo(staffId)
    let doctorFirstName = staffInfo.name[0]
    // 根据 chatRoomId 获取处理过后的聊天内容
    this.findContentByChatRoomId(chatRoomId)
    
    this.setData({
      chatRoomId,
      staffId,
      userId,
      userInfo,
      doctorInfo:staffInfo,
      doctorFirstName
    })
  },
  async onUnload(){
    let {staffId,count} = this.data
    if(count != 0 ){
      await updateDoctorToDoTasks(staffId,"add")
    }
  },
  // 根据id查聊天室中的content
  async findContentByChatRoomId(chatRoomId){
    let chatContent = await findChatRoomContentById(chatRoomId)
    chatContent.reverse()
    this.setData({
      chatContent,
      inputValue:"",
    })
    this.scrollToButtom()
  },

  // 发送消息
  async sendMsg(){
    const {inputValue,userId,chatRoomId,count} = this.data

    if (inputValue == "") {
      Toast.fail("输入内容为空")
    }else{
      // 更新服务器端content
      let updateRet = await updateChatRoomContent(chatRoomId,{
        id:userId,
        value:inputValue,
        time:formatTime(Date.now())
      })

      // 通知对方与自己有新消息
      if(updateRet.code == 201){
        send({
          from:"user",
          haveNewMsg:true,
          chatRoomId
        })
      }

      // 表示用户发过消息
      this.setData({
        count:count++
      })
    }
  },

  // 滚动至底部
  scrollToButtom(){
    wx.createSelectorQuery()
    .select('#scrollview')
    .node()
    .exec((res) => {
      const scrollView = res[0].node;
      console.log(scrollView,scrollView.height);
      scrollView.scrollTo({
        top:1200
      })
    })
  }
})